/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.sge.qbase;

import java.util.Collection;

import jp.aist.gtrc.plus.reserve.ReserveException;
import jp.aist.gtrc.plus.reserve.ReserveId;
import jp.aist.gtrc.plus.reserve.ReserveInfo;
import jp.aist.gtrc.plus.reserve.ReserveNodeSet;
import jp.aist.gtrc.plus.reserve.ReserveOperationType;
import jp.aist.gtrc.plus.reserve.ReserveRequest;
import jp.aist.gtrc.plus.scheduler.node.NodeInfo;
import jp.aist.gtrc.plus.scheduler.node.NodeManager;
import jp.aist.gtrc.plus.scheduler.util.CmdUtil;
import jp.aist.gtrc.plus.scheduler.util.CollectionUtil;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;

public class SGEQbaseReserveInfo extends ReserveInfo {

	private static final long serialVersionUID = -7407677492134975434L;

	private transient SGEQbaseReserveManager rsvMgr;

	public SGEQbaseReserveInfo(ReserveId id, ReserveRequest req,
			ReserveNodeSet rsvNodeSet, SGEQbaseReserveManager rsvMgr) throws ReserveException {

		super(id, req, rsvNodeSet);
		this.rsvMgr = rsvMgr;

		registerNodes(rsvNodeSet);

	}

	public void recoverTransient(SGEQbaseReserveManager rsvMgr) {

		this.rsvMgr = rsvMgr;

	}

	protected String getHostList(ReserveNodeSet rsvNodeSet) {

		// NOTE: hostnames are separated by " "
		String[] nodes = rsvNodeSet.getNames();
		return CollectionUtil.isEmpty(nodes)
				? "NONE" : TextUtil.fromArray(nodes, " ");

	}

	private void registerNodes(ReserveNodeSet rsvNodeSet) throws ReserveException {

		if (rsvMgr == null) {
			return;
		}

		NodeManager nodeMgr = rsvMgr.getNodeManager();
		Collection<NodeInfo> allNodes = nodeMgr.getNodes();
		String[] names = new String[allNodes.size()];
		int i = 0;
		for (NodeInfo node : allNodes) {
			names[i] = node.getName();
			i++;
		}

		String allNodeNames = (i > 0)
				? TextUtil.fromArray(names, " ") : "NONE";

		/*
		 * usage: sge_rsvq_reg_nodes.sh $RSVID $HOSTLIST
		 * We always register all node names, ignore rsvNodeSet
		 */
		CmdUtil.runCommand(new String[]{
				"sge_rsvq_reg_nodes.sh",
				getReserveId().toString(),
				allNodeNames}
		);

	}

	private void unregisterNodes() throws ReserveException {

		/*
		 * usage: sge_rsvq_unreg_nodes.sh $RSVID
		 */
		CmdUtil.runCommand(new String[]{
				"sge_rsvq_unreg_nodes.sh",
				getReserveId().toString()}
		);

	}

	private ReserveOperationType getCurrentOperationType() {

		if (rsvMgr == null) {
			// not initialized yet
			return ReserveOperationType.reserve;
		} else {
			return rsvMgr.getCurrentOperation().getOperationType();
		}

	}

	protected void registerReservedNodes(ReserveNodeSet rsvNodeSet) throws ReserveException {

		ReserveNodeSet oldSet = getReserveNodeSet();

		super.registerReservedNodes(rsvNodeSet);

		switch (getCurrentOperationType()) {
		case cancel:
		case destroy:
			// fall-through to recover/modify reserved nodes
		case reserve:
		case modify:
			if ((rsvNodeSet != null) && (rsvNodeSet.equals(oldSet) == false)) {
				registerNodes(rsvNodeSet);
			}
			break;
		case idle:
		case remove:
			assert(false);
			break;
		default:
			assert(false);
			break;
		}

	}

	protected void unregisterReservedNodesForever() throws ReserveException {

		super.unregisterReservedNodesForever();

		switch (getCurrentOperationType()) {
		case cancel:
		case modify:
			try {
				unregisterNodes();
			} catch (ReserveException e) {
				// TODO ignore
			}
			break;
		case reserve:
			// abort of reserve was called.
			// don't call unregisterNodes() same as destroy etc.
			break;
		case idle:
			// reserve will be deleted by scheduling
			break;
		case destroy:
		case remove:
			// reserve queue will be removed soon,
			// don't call unregisterNodes()
			break;
		default:
			assert(false);
			break;
		}

	}

	protected void changeReserveRequest(ReserveRequest oldReq, ReserveRequest newReq) throws ReserveException {

		String oldUserNames = TextUtil.fromArray(oldReq.getUsers(), ",");
		String newUserNames = TextUtil.fromArray(newReq.getUsers(), ",");

		super.changeReserveRequest(oldReq, newReq);

		if (oldUserNames.equals(newUserNames) == false) {
			CmdUtil.runCommand(new String[]{
					"sge_rsvq_mod_users.sh",
					getReserveId().toString(),
					newUserNames});
		}

	}

	public String getSlotNumList() {

		// NOTE: don't specify node names
		return "1";

		/*
		 * Assume that we reserved
		 * 		host00.example.com (2 CPU) and host01.example.com (1 CPU),
		 * this method returns "1,[host00.example.com=2],[host01.example.com=1]"
		 * First "1" is ignored because it is default value.
		 */
		/*
		String list = "1,";
		for (NodeInfo node : getReservedNodeInfos()) {
			NodeStatus status = node.getStatus();
			list += "[" + status.getName() + "=" + status.getCPUNum() + "],";
		}
		return list.substring(0, list.length() -1);
		*/

	}

}
